<?php

declare(strict_types=1);

namespace core;

use PDO;
use PDOException;

/**
 * Base model class with PDO for database
 */
abstract class Model
{
    private static ?PDO $pdo = null;

    protected function getDb(): PDO
    {
        if (self::$pdo === null) {
            // Load config securely
            $config = require __DIR__ . '/../config/database.php';

            try {
                self::$pdo = new PDO(
                    "{$config['driver']}:host={$config['host']};dbname={$config['database']};charset=utf8mb4",
                    $config['username'],
                    $config['password'],
                    [
                        PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
                        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
                        PDO::ATTR_EMULATE_PREPARES   => false,  // Use real prepared statements for security
                        PDO::ATTR_STRINGIFY_FETCHES  => false,  // Optimize for native types
                    ]
                );
            } catch (PDOException $e) {
                throw new \Exception("Database connection failed: " . $e->getMessage(), 500);
            }
        }
        return self::$pdo;
    }

    protected function query(string $sql, array $params = []): array
    {
        $stmt = $this->getDb()->prepare($sql);
        $stmt->execute($params);
        return $stmt->fetchAll();
    }
}
